<template>
  <HotTable
    style="width: 110%"
    ref="hotTableComponent"
    :data="showStock.data"
    :settings="hotSettings"
  />
</template>

<script setup lang="ts">
import { HotTable } from '@handsontable/vue3'
import { ref, reactive, watch, nextTick } from 'vue'
import Handsontable from 'handsontable'
import 'handsontable/dist/handsontable.full.css'
import { inject } from 'vue'

// const sendToGrandPa = inject('sendToGrandPa')

const props = defineProps<{
  modelValue: any[],
  id:number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', payload: any[]): void
}>()


const showStock = reactive<{ data: any[] }>({ data: [] })


const hotTableComponent = ref<any>(null)


const warehouseData = ['广州云仓', '南昌云仓', '长沙云仓', '贵阳云仓', '武汉云仓', '西安云仓']
const fields = [
  { data: 'first' },
  { data: 'second' },
  { data: 'third' },
  { data: 'fourth' },
  { data: 'fifth' },
  { data: 'sixth' },
  { data: 'seventh' },
  { data: 'eighth' },
  { data: 'ninth' },
  { data: 'tenth' },
  { data: 'eleven' },
  { data: 'twelve' },
]


Handsontable.renderers.registerRenderer('negativeValueRenderer', (instance, td, row, col, prop, value) => {
  td.innerHTML = value == 0 || value === '' || value == null ? '' : String(value)
  }
)

 //  初始化云仓数据， 根据数据算合计
const initCurrentNum = () => {
  if (showStock.data == undefined || showStock?.data?.length <= 0) {
    console.log('2222',showStock.data)
    let newShowStock = [...showStock.data];
    warehouseData.forEach((row, index) => {
      newShowStock.push({
        wareName: row,
        shopNum:0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
        total:0
      })
    })
    newShowStock.push({
      wareName: "合计",
      shopNum:0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
    })

    showStock.data = newShowStock
    return
  }

  let total_avg_shop_num : number | string = 0;
  let total_stock = []
  let total_avg = []
  let total = [];

  fields.forEach((r,i) => {
    total_stock[r.data] = 0;
    total_avg[r.data] = 0;
    total[r.data] = 0;
  })
  let total_stock_num = 0
  let max_index = 6;
  showStock?.data?.forEach((row, index) => {
    let index_total = 0
    if (row.wareName !== "合计") {
      fields.forEach((r,i) => {
        index_total = index_total + parseInt((row[r.data] == '' || row[r.data] == null)  ? 0 : row[r.data])
        total[r.data] = total[r.data] + parseInt((row[r.data] == '' || row[r.data] == null)  ? 0 : row[r.data])
      })
      fields.forEach((r,i) => {
        showStock.data[max_index][r.data] = total[r.data]
      })
    } else {
      fields.forEach((r,i) => {
        index_total = index_total + parseInt((row[r.data] == '' || row[r.data] == null)  ? 0 : row[r.data])

      })
    }
    showStock.data[index].total = index_total

    let shopNum = showStock.data[index].shopNum <= 0 ? 0 : showStock.data[index].shopNum
    console.log('shop_numshop_num',shopNum)
    if (index < max_index) {
      showStock.data[index].shopNum = shopNum
      fields.forEach((r,i) => {
        total_stock[r.data] = total_stock[r.data] + showStock.data[index][r.data]
        showStock.data[max_index][r.data] = total_stock[r.data]
        total_stock_num = total_stock_num+showStock.data[index][r.data]
      })
      showStock.data[max_index]['total'] = total_stock_num

      total_avg_shop_num = total_avg_shop_num + parseInt(shopNum)
      console.log('total_avg_shop_num',total_avg_shop_num)
    } else {

      fields.forEach((r,i) => {
        total_avg[r.data] = total_avg_shop_num <= 0 ? 0 : ((showStock.data[max_index][r.data]) / total_avg_shop_num).toFixed(1)
      })
      showStock.data[max_index].shopNum = total_avg_shop_num
    }
  })

  // const  totalObject = {
  //   total: showStock.data.find(r => r.wareName === '合计')?.total,
  //   id: props.id,
  // }
  // console.log(totalObject.total);
  // sendToGrandPa({ msg: 'hi 爷爷', ts: totalObject })


}

watch(() =>props.modelValue, (val) => {

    showStock.data = props.modelValue
     initCurrentNum()
  },
  { immediate: true }
)


const highlight = reactive({ row: -1, col: -1 })
/* ---------- Handsontable 配置 ---------- */
const hotSettings: Handsontable.GridSettings = {
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  width: '100%',
  height: 250,
  colHeaders: [
    '仓库',
    '上<br>柜<br>数<br>',
    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42<br>均码',
    '铺货备注',
    '窗口<br>等级<br>备注',
    '店铺<br>等级',
    '要求交期',
    '合计',
  ],
  columns: [
    { data: 'wareName', width: 70, readOnly: true },
    { data: 'shopNum', width: 40, type: 'numeric' },
    { data: 'first', width: 40, type: 'numeric' },
    { data: 'second', width: 40, type: 'numeric' },
    { data: 'third', width: 40, type: 'numeric' },
    { data: 'fourth', width: 40, type: 'numeric' },
    { data: 'fifth', width: 40, type: 'numeric' },
    { data: 'sixth', width: 40, type: 'numeric' },
    { data: 'seventh', width: 40, type: 'numeric' },
    { data: 'eighth', width: 40, type: 'numeric' },
    { data: 'ninth', width: 40, type: 'numeric' },
    { data: 'tenth', width: 40, type: 'numeric' },
    { data: 'eleven', width: 40, type: 'numeric' },
    { data: 'twelve', width: 40, type: 'numeric' },
    { data: 'shippingRemark', width: 80 },
    { data: 'windowLevelRemark', width: 80 },
    { data: 'use_shop_level', width: 70 },
    { data: 'goDeadLine', width: 85, type: 'date', dateFormat: 'YYYY-MM-DD', correctFormat: true },
    { data: 'total', width: 50, type: 'numeric', readOnly: true },
  ],
  cells(row, col, prop) {
    const cellProps: any = {}
    cellProps.renderer = 'negativeValueRenderer'
    return cellProps
  },
  afterChange(change, source) {
     if (source === 'loadData') return
    initCurrentNum() // 重新计算合计并 syncBack
  },
  afterSelection(row, col) {
    highlight.row = row
    highlight.col = col
  },
  fillHandle: 'vertical',
  contextMenu: {
    items: { separator: Handsontable.plugins.ContextMenu.SEPARATOR },
  },
  copyable: true,
  copyPaste: true,
  manualColumnResize: true,
  manualRowMove: true,
}
</script>

<style scoped>
/* 如需覆盖 handsontable 样式可写在这里 */
</style>
